<?php
/**
 * @Author: king
 * @Last Modified by:   king
 * Date: 2018/6/6
 * Time: 17:38
 */

namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use Cache;

class UserMsg extends Base
{
    protected $table = 'user_msg';

    /**
     * 获取当前用户的所有已读信息id
     */
    public function getUserMessage($map = [])
    {
        $uid = $map['uid'];

        $where['type'] = 1;

        //获取系统消息id
        $system_msg_id = $this->get_user_msg_id(['uid' => $uid, 'type' => 1]);
        //获取服务消息id
        $server_msg_id = $this->get_user_msg_id(['uid' => $uid, 'type' => 2]);
        $server_msg_id = $this->get_user_msg_id(['uid' => $uid, 'type' => 3]);

        $data = $system_msg_id['total'] + $server_msg_id['total']+ $server_msg_id['total'];

        return $data;
    }

    /**
     * 获取当前用户已读的系统 / 服务信息id
     */
    public function get_user_msg_id($map = [])
    {
        switch ($map['type'])
        {
            case 1:
                $where['m.type'] = 1;
                break;
            case 2:
                $where['m.type'] = 2;
                 break;
            case 3:
                $where['m.type'] = 3;
        }

        $uid = $map['uid'];

        $mid = false;

        if (intval($this->cache_on) >= 1 && Cache::has($uid.'_user_read_message_id_' . $map['type']))
        {
            $mid = Cache::get($uid . '_user_read_message_id_' . $map['type']);
        }

        // 获取当前消息的所有消息的id
        if ($mid === false)
        {
            try
            {
                $data1 = $this->from('user_msg as um')
                    ->select('um.mid')
                    ->join('message_center as m', 'um.mid','=','m.id', 'INNER')
                    ->where($where)
                    ->where('um.uid', $map['uid'])
                    ->orWhere('um.uid', 0)
                    ->get();
                $data1 = json_decode(json_encode($data1, true), true);

                // 将消息id组成字符串
                if (!empty($data1)) foreach ($data1 as $acl) $mid .= $acl['mid'] . ',';
                else $mid = '';

                // 缓存消息id,根据消息id
                if (intval($this->cache_on) >= 1)
                    Cache::set($uid . '_user_read_message_id_' . $map['type'], $mid, 86400 * 3);

            } catch (\Exception $e)
            {
                $mid = '';// 消息列表默认为空
            }

        }

        // 将消息id转为数组
        $mid = explode(',', $mid);

        // 去除数组最后一个元素
        array_pop($mid);

        // 统计有多少消息
        $total = count($mid);

        $data['total'] = $total;
        $data['data'] = $mid;

        return $data;
    }

}
